<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>requestAnimationFrame使用</title>
</head>

<body>
    <!-- 不需要设置时间间隔 使用一个回调函数作为参数 -->
    <div id="myDiv" style="background-color: lightblue;width: 0;height: 20px;line-height: 20px;">0%</div>
    <button id="btn">run</button>
    <script>
        var myDiv = document.getElementById("myDiv")
        var btn = document.getElementById("btn")
        var timer;
        btn.onclick = function () {

            myDiv.style.width = '0';
            cancelAnimationFrame(timer);
            timer = requestAnimationFrame(function fn() {
                if (parseInt(myDiv.style.width) < 500) {
                    myDiv.style.width = parseInt(myDiv.style.width) + 5 + 'px';
                    myDiv.innerHTML = parseInt(myDiv.style.width) / 5 + '%';
                    timer = requestAnimationFrame(fn);
                } else {
                    cancelAnimationFrame(timer);
                }
            });
        }
    </script>
</body>

</html>